package nz.ac.massey.cs.se400_2013.ass3.plugin;

import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.event.ChangeEvent;

public abstract class BasicEditor extends JPanel{
	
	private ArrayList<ChangeListener> listeners = new ArrayList<ChangeListener>();
	
	public void addChangeListener(ChangeListener listener){
		this.listeners.add(listener);
	}
	
	public void fireChanges(){
		for(ChangeListener listener : this.listeners){
			listener.change();
		}
	}
	
	public void addChangeHandlers(){
		for(Component c : this.getComponents()){
			if(c.getClass() == JTextField.class || c.getClass() == JSpinner.class){
				c.addKeyListener(new ChangeHandler());
			}
			if(c.getClass() == JSpinner.class){
				((JSpinner)c).addChangeListener(new ChangeHandler());
			}
		}
	}
	
	private class ChangeHandler implements KeyListener, javax.swing.event.ChangeListener{

		@Override
		public void keyPressed(KeyEvent arg0) {
		}

		@Override
		public void keyReleased(KeyEvent arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void keyTyped(KeyEvent arg0) {
			System.out.println("key pressed");
			fireChanges();
			
		}

		@Override
		public void stateChanged(ChangeEvent arg0) {
			fireChanges();
		}
		
	}
}
